import * as Api from '@/api/user'
import authority from '@/utils/authority'

const state = {
	user: authority.get() || {},
}

const getters = {
	isLogin(state) {
		return !!state.token
	},
}

const mutations = {
	SET_USER: (state, payload = {}) => {
		Object.assign(state, payload)
	},
}

const actions = {
	// 登录
	async login({ commit }, { username = '', password = '' }) {
		const { user = {}, token } = await Api.login({
			username: username.trim(),
			password,
		})
		user.token = token
		authority.set(user)
		commit('SET_USER', { user })
	},
	// 微信登录
	async wxLogin({ commit }, code = '') {
		if (!code) return Promise.reject('code not found')
		const { user, token } = await Api.wxLogin(code)
		user.token = token
		user.username = user.nickname
		authority.set(user)
		commit('SET_USER', { user })
	},
	// 登出
	async logout({ commit }) {
		await Api.logout()
		authority.clear()
		commit('SET_USER', {
			user: {},
		})
	},
}

export default {
	state,
	getters,
	mutations,
	actions,
}
